/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.cognition.util.j2me.io;

/**
 *
 * @author richard
 */
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;

public class Sender extends Thread {
    private DatagramConnection dc;

    private String address;

    private byte[] message;

    public Sender(DatagramConnection dc) {
	this.dc = dc;
	start();
    }

    public synchronized void send(String addr, byte[] msg) {
	address = addr;
	message = msg;
	notify();
    }

    public synchronized void run() {
	while (true) {
	    // If no client to deal, wait until one connects
	    if (message == null) {
		try {
		    wait();
		} catch (InterruptedException e) {
		}
	    }

	    try {
		Datagram dg = null;

		// Are we a sender thread for the client ? If so then there's
		// no address parameter
		if (address == null) {
		    dg = dc.newDatagram(message, message.length);
		} else {
		    dg = dc.newDatagram(message, message.length, address);
		}

		dc.send(dg);
	    } catch (Exception ioe) {
		ioe.printStackTrace();
	    }

	    // Completed client handling, return handler to pool and
	    // mark for wait
	    message = null;
	}
    }
}
